<template>
  <div>
  <div ref="container"
       style="width:100%; height: 30%; background-color: #000000;margin:0 auto;position: relative;z-index:999">
    <div style="width:100%; padding-top: 56.25%; position: relative;"></div>
    <div class="buttons-box" id="buttonsBox">
      <div class="buttons-box-left">
        <i v-if="!playing" class="iconfont icon-play jessibuca-btn" @click="playBtnClick"></i>
        <i v-if="playing" class="iconfont icon-pause jessibuca-btn" @click="pause"></i>
        <i class="iconfont icon-stop jessibuca-btn" @click="destroy"></i>
        <i v-if="isNotMute" class="iconfont icon-audio-high jessibuca-btn" @click="mute()"></i>
        <i v-if="!isNotMute" class="iconfont icon-audio-mute jessibuca-btn" @click="cancelMute()"></i>
      </div>
      <div class="buttons-box-right">
        <span class="jessibuca-btn">{{ kBps }} kb/s</span>
        <!--          <i class="iconfont icon-file-record1 jessibuca-btn"></i>-->
        <!--          <i class="iconfont icon-xiangqing2 jessibuca-btn" ></i>-->
<!--        <i class="iconfont icon-camera1196054easyiconnet jessibuca-btn" @click="screenshot"-->
<!--           style="font-size: 1rem !important"></i>-->
        <i class="iconfont icon-shuaxin11 jessibuca-btn" @click="playBtnClick"></i>
        <i v-if="!fullscreen" class="iconfont icon-weibiaoti10 jessibuca-btn" @click="fullscreenSwich"></i>
        <i v-if="fullscreen" class="iconfont icon-weibiaoti11 jessibuca-btn" @click="fullscreenSwich"></i>
      </div>
    </div>
  </div>
    <div id="date-switch-container-wrap" class="date-switch-container-wrap" style="">
      <div class="date-switch-container">
        <div class="current-date" id="current-date">{{getTitle()}}录像</div>
        <div class="date-container" @click="showChooseDate">
          <label for="date">
            <div class="date-icon"></div>
          </label>
          <el-date-picker style="margin-left: -23px;"
                          v-model="chooseDate" prefix-icon="none" value-format="yyyy-MM-dd"
            type="date"  ref="pickerDate" @change="changeChooseDate"
            >
          </el-date-picker>
        </div>

      </div>
    </div>
    <div id="rec-type-container-wrap" class="rec-type-container-wrap" style="">
      <div class="rec-type-container">
        <div class="rec-type-text">共<span id="recCount">{{detailFiles.length}}</span>个录像</div>
        <div class="rec-type-switch">
          <label>
            <input type="checkbox" name="type" id="cloudType" v-model="videoType" hidden="">
            <label for="cloudType" class="advice">
          <span>
          <svg fill="#CCCCCC" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 0 20 20">
            <path class="st0" d="M12.6,5c-2.3,0.1-4.3,1.4-5.3,3.3L7.2,8.6c-2.4,0.5-4.1,2.5-4.1,4.9c0,2.8,2.4,5,5.2,5h9.9
            c2.4,0,4.3-1.9,4.3-4.2l0-0.2c-0.1-2-1.6-3.5-3.5-3.9l-0.1,0l0-0.2c-0.4-2.8-3-5-6.1-5L12.6,5z"></path>
          </svg>
        </span>
              <span>
          <svg fill="#CCCCCC" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 0 20 20">
            <path id="形状结合" class="st0" d="M14.3,4c0.6,0,1.2,0.2,1.7,0.7l0,0L18.3,7C18.7,7.4,19,8,19,8.6l0,0v9c0,1.3-1.1,2.3-2.4,2.3
	l0,0H8.4C7.1,20,6,19,6,17.7l0,0V6.3C6,5,7.1,4,8.4,4l0,0H14.3z M9.7,7.2C9.3,7.2,8.9,7.6,8.9,8l0,0v2.5l0,0.1
	c0,0.4,0.4,0.6,0.7,0.6c0.4,0,0.8-0.3,0.8-0.8l0,0V8l0-0.1C10.4,7.5,10,7.2,9.7,7.2z M12.2,7.2c-0.4,0-0.8,0.3-0.8,0.8l0,0v2.5
	l0,0.1c0,0.4,0.4,0.6,0.7,0.6c0.4,0,0.8-0.3,0.8-0.8l0,0V8l0-0.1C12.9,7.5,12.5,7.2,12.2,7.2z M14.7,7.2c-0.4,0-0.8,0.3-0.8,0.8l0,0
	v2.5l0,0.1c0,0.4,0.4,0.6,0.7,0.6c0.4,0,0.8-0.3,0.8-0.8l0,0V8l0-0.1C15.4,7.5,15,7.2,14.7,7.2z"></path>
          </svg>
        </span>
            </label>
          </label>
        </div>
      </div>
    </div>
    <div id="mobile-rec-wrap" class="mobileRec-wrap" v-loading="recordsLoading" >
      <div class="time-line-container">
        <div class="parentDiv">


        <el-slider
          class="playtime-slider"
          v-model="playTime"
          vertical
          id="playtimeSlider"
          :disabled="detailFiles.length === 0"
          :min="sliderMIn"
          :max="sliderMax"
          :range="true"
          :format-tooltip="playTimeFormat"
          @change="playTimeChange"
          :marks="playTimeSliderMarks">
        </el-slider>
        <div class="slider-val-box">
          <div class="slider-val" v-for="item of detailFiles" :style="'height:' + getDataWidth(item) + '%; bottom:' + getDataLeft(item) + '%'"></div>
        </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
let jessibucaPlayer = {};
import Dialog from 'vant/lib/dialog';
import 'vant/lib/dialog/style';
import moment from "moment";
export default {
  name: 'h5replay',
  data() {
    return {
      playing: false,
      isNotMute: false,
      quieting: false,
      fullscreen: false,
      loaded: false, // mute
      speed: 0,
      performance: "", // 工作情况
      kBps: 0,
      btnDom: null,
      videoInfo: null,
      volume: 1,
      rotate: 0,
      vod: true, // 点播
      forceNoOffscreen: false,
      deviceId:'',
      channelId:"",
      chooseDate:moment().format('YYYY-MM-DD'),
      recordsLoading:false,
      videoType:1,
      playTime: null,
      timeRange: null,
      startTime: null,
      endTime: null,
      detailFiles:[],
      sliderMIn: 0,
      sliderMax: 86400,
      playTimeSliderMarks: {
        0: "00:00",
        3600: "01:00",
        7200: "02:00",
        10800: "03:00",
        14400: "04:00",
        18000: "05:00",
        21600: "06:00",
        25200: "07:00",
        28800: "08:00",
        32400: "09:00",
        36000: "10:00",
        39600: "11:00",
        43200: "12:00",
        46800: "13:00",
        50400: "14:00",
        54000: "15:00",
        57600: "16:00",
        61200: "17:00",
        64800: "18:00",
        68400: "19:00",
        72000: "20:00",
        75600: "21:00",
        79200: "22:00",
        82800: "23:00",
        86400: "24:00",
      },
      videoUrl:'',
      streamInfo:{},
      showconfirm:false
    };
  },
  created() {

  },
  mounted(){
    let url = decodeURIComponent(this.$route.params.url)
    let name = this.$route.query.name || '国标28181';
    this.$nextTick(() => {
      console.log(2222)
      document.title = name;
      this.updatePlayerDomSize()
      window.onresize = this.updatePlayerDomSize
      const params = url.substring(url.indexOf('/rtp/') + 5, url.indexOf('.live.flv')).split('_');
      this.deviceId = params[0];
      this.channelId = params[1];
      this.changeChooseDate();
      window.addEventListener('beforeunload', this.stopPlayRecord)
      this.btnDom = document.getElementById("buttonsBox");
    })
  },
  methods: {
    getTitle(){
      if(this.chooseDate===moment().format('YYYY-MM-DD')){
        return '今日'
      }
      return moment(this.chooseDate).format("YYYY年MM月DD日")
    },
    showChooseDate(){
      // 手动打开日期选择器
      this.$nextTick(() => {
        this.$refs.pickerDate.handleFocus();
        this.$refs.pickerDate.pickerVisible = true;
      });
    },
    isWeChat(){
      //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
      var ua = window.navigator.userAgent.toLowerCase();
      //通过正则表达式匹配ua中是否含有MicroMessenger字符串
      if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
      }else{
        return false;
      }
    },
    changeChooseDate(){
      if (!this.chooseDate) {
        return;
      }
      this.detailFiles = [];
      this.setTime(this.chooseDate + " 00:00:00", this.chooseDate + " 23:59:59");
      this.recordsLoading = true;

      this.$axios({
        method: 'get',
        url: '/api/gb_record/query/' + this.deviceId + '/' + this.channelId + '?startTime=' + this.startTime + '&endTime=' + this.endTime
      }).then((res)=>{
        this.recordsLoading = false;
        if(res.data.code === 0) {
          // 处理时间信息
          this.detailFiles = res.data.data.recordList;
          //默认播放最后一调
          if(this.detailFiles.length > 0) {
            if(this.isWeChat()){
              this.showconfirm = true;
            }
            var lastStartTime = this.detailFiles[0].startTime.split(' ')[1].split(':');
            //计算总的秒数
            this.playTimeChange([parseInt(lastStartTime[0]) * 3600 + parseInt(lastStartTime[1]) * 60 + parseInt(lastStartTime[2]),this.sliderMax]);
          }else{
            this.$message({
              showClose: true,
              message: this.getTitle()+"无录像",
              type: "info",
            });
          }


        }else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }

      }).catch((e)=> {
        this.recordsLoading = false;
        // that.videoHistory.searchHistoryResult = falsificationData.recordData;
      });
    },
    moment: function (v) {
      return moment(v)
    },
    setTime: function (startTime, endTime){
      this.startTime = startTime;
      this.endTime = endTime;
      let start = (new Date(this.startTime).getTime() - new Date(this.chooseDate + " 00:00:00").getTime())/1000;
      let end = (new Date(this.endTime).getTime() - new Date(this.chooseDate + " 00:00:00").getTime())/1000;
      console.log(start)
      console.log(end)
      this.playTime = [start, end];
      this.timeRange = [startTime, endTime];
    },
    playTimeChange(val){
      console.log('playTimeChange',val)

      let startTimeStr = moment(new Date(this.chooseDate + " 00:00:00").getTime() + val[0]*1000).format("YYYY-MM-DD HH:mm:ss");
      let endTimeStr = moment(new Date(this.chooseDate + " 00:00:00").getTime() + val[1]*1000).format("YYYY-MM-DD HH:mm:ss");

      this.setTime(startTimeStr, endTimeStr)

      this.playRecord();
    },
    stopPlayRecord: function (callback) {
      console.log("停止录像回放")
      if (this.streamId !== "") {
        this.pause();
        this.videoUrl = '';
        this.$axios({
          method: 'get',
          url: '/api/playback/stop/' + this.deviceId + "/" + this.channelId + "/" + this.streamId
        }).then(function (res) {
          if (callback) callback()
        });
      }

    },
    playRecord: function () {

      if (this.streamId !== "") {
        this.stopPlayRecord(()=> {
          this.streamId = "";
          this.playRecord();
        })
      } else {
        this.$axios({
          method: 'get',
          url: '/api/playback/start/' + this.deviceId + '/' + this.channelId + '?startTime=' + this.startTime + '&endTime=' +
            this.endTime
        }).then((res)=> {
          if (res.data.code === 0) {
            this.streamInfo = res.data.data;
            this.app = this.streamInfo.app;
            this.streamId = this.streamInfo.stream;
            this.mediaServerId = this.streamInfo.mediaServerId;
            this.ssrc = this.streamInfo.ssrc;
            this.videoUrl = this.getUrlByStreamInfo();
            if(this.showconfirm){
              Dialog.confirm({
                title: '提示',
                message: '视频加载完成, 点击确定开始预览',
              })
                .then(() => {
                  this.showconfirm = false;
                  this.play(this.videoUrl)
                })
                .catch(() => {
                  // on cancel
                  this.showconfirm = false;
                });
            }else{
              this.play(this.videoUrl)
            }
            this.hasAudio = this.streamInfo.tracks && this.streamInfo.tracks.length > 1
          }else {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error",
            });
          }
        });
      }
    },
    getUrlByStreamInfo(){
      if (location.protocol === "https:") {
        this.videoUrl = this.streamInfo["wss_flv"]
      }else {
        this.videoUrl = this.streamInfo["ws_flv"]
      }
      return this.videoUrl;

    },
    playTimeFormat(val){
      let h = parseInt(val/3600);
      let m = parseInt((val - h*3600)/60);
      let s = parseInt(val - h*3600 - m*60);

      let hStr = h;
      let mStr = m;
      let sStr = s;
      if (h < 10) {
        hStr = "0" + hStr;
      }
      if (m < 10) {
        mStr = "0" + mStr;s
      }
      if (s < 10) {
        sStr = "0" + sStr;
      }
      return hStr + ":" + mStr + ":" + sStr
    },
    getTimeForFile(file){
      let startTime = new Date(file.startTime);
      let endTime = new Date(file.endTime);
      return [startTime, endTime, endTime.getTime() - startTime.getTime()];
    },
    getDataWidth(item){
      let timeForFile = this.getTimeForFile(item);
      let result = (timeForFile[2])/((this.sliderMax - this.sliderMIn)*1000)
      return result*100
    },
    getDataLeft(item){
      let timeForFile = this.getTimeForFile(item);
      let differenceTime = timeForFile[0].getTime() - new Date(this.chooseDate + " 00:00:00").getTime()
      return parseFloat((differenceTime - this.sliderMIn * 1000)/((this.sliderMax - this.sliderMIn)*1000))*100   ;
    },
    updatePlayerDomSize() {
      let dom = this.$refs.container;
      let width = dom.parentNode.clientWidth
      let height = (9 / 16) * width
      console.log(height)

      console.log(dom.clientHeight)
      if (height > dom.clientHeight) {
        height = dom.clientHeight
        width = (16 / 9) * height
      }
      if (width > 0 && height > 0) {
        dom.style.width = width + 'px';
        dom.style.height = height + "px";
        dom.style.paddingTop = 0;
        console.log(width)
        console.log(height)
      }
    },

    create() {
      let options = {
        container: this.$refs.container,
        autoWasm: true,
        background: "",
        controlAutoHide: false,
        debug: false,
        decoder: "static/js/jessibuca/decoder.js",
        forceNoOffscreen: false,
        hasAudio: typeof (this.hasAudio) == "undefined" ? true : this.hasAudio,
        heartTimeout: 5,
        heartTimeoutReplay: true,
        heartTimeoutReplayTimes: 3,
        hiddenAutoPause: false,
        hotKey: true,
        isFlv: false,
        isFullResize: false,
        isNotMute: this.isNotMute,
        isResize: false,
        keepScreenOn: true,
        loadingText: "请稍等, 视频加载中......",
        loadingTimeout: 10,
        loadingTimeoutReplay: true,
        loadingTimeoutReplayTimes: 3,
        openWebglAlignment: false,
        operateBtns: {
          fullscreen: false,
          screenshot: false,
          play: false,
          audio: false,
          record: false
        },
        recordType: "mp4",
        rotate: 0,
        showBandwidth: false,
        supportDblclickFullscreen: false,
        timeout: 10,
        useMSE: true,
        useWCS: location.hostname === "localhost" || location.protocol === "https:",
        useWebFullScreen: true,
        videoBuffer: 0.1,
        wasmDecodeErrorReplay: true,
        wcsUseVideoRender: true
      };
      console.log("Jessibuca -> options: ", options);
      jessibucaPlayer[this._uid] = new window.Jessibuca({...options});

      let jessibuca = jessibucaPlayer[this._uid];
      let _this = this;
      jessibuca.on("pause", function () {
        _this.playing = false;
      });
      jessibuca.on("play", function () {
        _this.playing = true;
      });
      jessibuca.on("fullscreen", function (msg) {
        _this.fullscreen = msg
      });
      jessibuca.on("mute", function (msg) {
        _this.isNotMute = !msg;
      });
      jessibuca.on("performance", function (performance) {
        let show = "卡顿";
        if (performance === 2) {
          show = "非常流畅";
        } else if (performance === 1) {
          show = "流畅";
        }
        _this.performance = show;
      });
      jessibuca.on('kBps', function (kBps) {
        _this.kBps = Math.round(kBps);
      });
      jessibuca.on("videoInfo", function (msg) {
        console.log("Jessibuca -> videoInfo: ", msg);
      });
      jessibuca.on("audioInfo", function (msg) {
        console.log("Jessibuca -> audioInfo: ", msg);
      });
      jessibuca.on("error", function (msg) {
        console.log("Jessibuca -> error: ", msg);
      });
      jessibuca.on("timeout", function (msg) {
        console.log("Jessibuca -> timeout: ", msg);
      });
      jessibuca.on("loadingTimeout", function (msg) {
        console.log("Jessibuca -> timeout: ", msg);
      });
      jessibuca.on("delayTimeout", function (msg) {
        console.log("Jessibuca -> timeout: ", msg);
      });
      jessibuca.on("playToRenderTimes", function (msg) {
        console.log("Jessibuca -> playToRenderTimes: ", msg);
      });
    },
    playBtnClick: function (event) {
      this.play(this.videoUrl)
    },
    play: function (url) {
      if(!url){
        return
      }
      console.log("Jessibuca -> url: ", url);
      if (jessibucaPlayer[this._uid]) {
        this.destroy();
      }
      this.create();
      jessibucaPlayer[this._uid].on("play", () => {
        this.playing = true;
        this.loaded = true;
        this.quieting = jessibuca.quieting;
      });
      if (jessibucaPlayer[this._uid].hasLoaded()) {
          jessibucaPlayer[this._uid].play(url);
      } else {
        jessibucaPlayer[this._uid].on("load", () => {
            jessibucaPlayer[this._uid].play(url);
        });
      }
    },
    pause: function () {
      if (jessibucaPlayer[this._uid]) {
        jessibucaPlayer[this._uid].pause();
      }
      this.playing = false;
      this.err = "";
      this.performance = "";
    },
    screenshot: function () {
      if (jessibucaPlayer[this._uid]) {
        jessibucaPlayer[this._uid].screenshot();
      }
    },
    mute: function () {
      if (jessibucaPlayer[this._uid]) {
        jessibucaPlayer[this._uid].mute();
      }
    },
    cancelMute: function () {
      if (jessibucaPlayer[this._uid]) {
        jessibucaPlayer[this._uid].cancelMute();
      }
    },
    destroy: function () {
      if (jessibucaPlayer[this._uid]) {
        jessibucaPlayer[this._uid].destroy();
      }
      if (document.getElementById("buttonsBox") == null) {
        this.$refs.container.appendChild(this.btnDom)
      }
      jessibucaPlayer[this._uid] = null;
      this.playing = false;
      this.err = "";
      this.performance = "";
      window.removeEventListener('beforeunload', this.stopPlayRecord)
    },
    fullscreenSwich: function () {
      let isFull = this.isFullscreen()
      jessibucaPlayer[this._uid].setFullscreen(!isFull)
      this.fullscreen = !isFull;
    },
    isFullscreen: function () {
      return document.getElementsByClassName('jessibuca-container')[0].className.indexOf('jessibuca-fullscreen-web')!=-1 ||
        document.msFullscreenElement ||
        document.mozFullScreenElement ||
        document.webkitFullscreenElement || false;
    }
  },
  destroyed() {
    if (jessibucaPlayer[this._uid]) {
      jessibucaPlayer[this._uid].destroy();
    }
    this.playing = false;
    this.loaded = false;
    this.performance = "";
  },
}
</script>

<style>
.buttons-box {
  width: 100%;
  height: 28px;
  background-color: rgba(43, 51, 63, 0.7);
  position: absolute;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  left: 0;
  bottom: 0;
  user-select: none;
  z-index: 10;
}

.jessibuca-btn {
  width: 20px;
  color: rgb(255, 255, 255);
  line-height: 27px;
  margin: 0px 10px;
  padding: 0px 2px;
  cursor: pointer;
  text-align: center;
  font-size: 0.8rem !important;
}

.buttons-box-right {
  position: absolute;
  right: 0;
}


html,body{
    padding: 0;
    margin: 0;
    text-align: center;
    background: #FFFFFF;
    overflow: hidden;
}


body{
  padding: 0;
  margin: 0;
}

.date-switch-container {
  height: 40px;
  position: relative;
  text-align: center;
  margin: 20px 10px;
}

.date-switch-container .current-date {
  line-height: 40px;
  height: 22px;
  font-size: 16px;
  color: #2C2C2C;
  text-align: center;
  font-weight: bold;
}

.date-container {
  width: 40px;
  height: 40px;
  position: absolute;
  right: 0;
  top: 0;
}

.rec-type-container {
  display: flex;
  justify-content: space-between;
}

.rec-type-container .rec-type-text {
  padding: 0 15px;
  font-size: 12px;
  color: #2C2C2C;
}

.rec-type-container .rec-type-switch {
  padding: 0 20px;
}

.date-container input {
  position: absolute;
  opacity: 0;
  display: none;
  width: 40px;
  height: 40px;
  z-index: 10;
  left: 0;
}

.date-container label {
  position: absolute;
  left: 0;
  top: 0;
  /* display: none; */
  z-index: 0;
}

.date-icon {
  display: inline-block;
  width: 40px;
  height: 40px;
  background: url('~@static/images/filter.png') no-repeat 100% 100%;
}
.select-container {
  padding: 10px;
  display: flex;
  justify-content: space-between;
}

.advice {
  height: 24px;
  width: 70px;
  display: flex;
  justify-content: space-between;
  line-height: 24px;
  background: #F8F8F8;
  border-radius: 8px;
}

.advice span {
  width: 40px;
  display: inline-block;
}

input[type="checkbox"]:not(:checked)+.advice span:first-child {
  box-shadow: 0px 2px 5px 0px rgb(23 45 101 / 20%);
  border-radius: 8px;
  text-align: center;

}

input[type="checkbox"]:checked+.advice span:last-child {
  box-shadow: 0px 2px 5px 0px rgb(23 45 101 / 20%);
  border-radius: 8px;
  text-align: center;
}

input[type="checkbox"]:not(:checked)+.advice span:first-child svg {
  fill: #648FFC !important;
}

input[type="checkbox"]:checked+.advice span:last-child svg {
  fill: #648FFC !important;
}
#app{
  background: #FFFFFF!important;
}
.time-line-container {
  height: 300px;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.time-line-container::-webkit-scrollbar {
  display: none;
}
.parentDiv{
  height:1506px;
  position: relative;
}
.el-slider__runway {
  background-color:rgba(206, 206, 206, 0.47) !important;
}
.el-slider__bar {
  background-color: rgba(153, 153, 153, 0) !important;
}
.playtime-slider {
  z-index: 100;
  height: 100%;
  margin-top:10px;
}
.slider-val-box{
  width: 6px;
  position: absolute;
  height: 100%;
  bottom: 0;
  left: 16px;
}
.slider-val{
  width: 6px;
  background-color: #007CFF;
  position: absolute;
}
.el-tooltip__popper{
  z-index: 0!important;
}
</style>
